package com.heima.behavior.service.impl;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApUnlikesBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnlikesBehaviorService;
import com.heima.common.constants.message.HotArticleConstants;
import com.heima.model.article.mess.UpdateArticleMess;
import com.heima.model.behavior.dto.UnLikesBehaviorDto;
import com.heima.model.behavior.pojo.ApBehaviorEntry;
import com.heima.model.behavior.pojo.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojo.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ApUnlikesBehaviorServiceImpl extends ServiceImpl<ApUnlikesBehaviorMapper, ApUnlikesBehavior>implements ApUnlikesBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Override
    public ResponseResult unlike(UnLikesBehaviorDto dto) {
        //检查参数
        if (dto.getArticleId()==null||(dto.getType()!=0&&dto.getType()!=1)){

            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询行为实体数据
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user == null ? null : user.getId(), dto.getEquipmentId());


        if (apBehaviorEntry==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的实体行为数据不存在");
        }
        //根据操作类型,进行对应的操作
        if (dto.getType().intValue()==0){
            ApUnlikesBehavior one = this.getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery()
                    .eq(ApUnlikesBehavior::getEntryId, apBehaviorEntry.getId())
                    .eq(ApUnlikesBehavior::getArticleId, dto.getArticleId()));

            if (one!=null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"请勿重复操作");
            }

            one=new ApUnlikesBehavior();
            one.setEntryId(apBehaviorEntry.getId());
            one.setArticleId(dto.getArticleId());
            one.setType((short)0);
            one.setCreatedTime(new Date());
            this.save(one);
        }else {

            this.remove(Wrappers.<ApUnlikesBehavior>lambdaQuery()
                    .eq(ApUnlikesBehavior::getEntryId,apBehaviorEntry.getId())
                    .eq(ApUnlikesBehavior::getArticleId,dto.getArticleId()));
        }

        return ResponseResult.okResult();
    }
}
